package com.bestdata.TD440.util;

/**
 * CRC16校验
 * @author chizhenyu
 * @date 2020年12月21日11:05:51
 */
public class CRC16Util {


    /**
     * 振动采集CRC16校验
     * @author chizhenyu
     * @return
     */
    public static Integer CRC16XOR(String resData){

        byte[] bytes = hexStringToByteArray(resData);

        int temp = 0;
        for (int i =0;i< bytes.length; i++) {
            temp ^= bytes[i];
        }
        return temp;
    }

    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i+1), 16));
        }
        return bytes;
    }

}
